import urllib
import json

import config


def get_response(msg):
    return auto_reply(msg)


def auto_reply(msg):

    url = "http://www.tuling123.com/openapi/api"
    data = {'key': '3c23287d10b140f7b8ab639ccfbce960',
            "info": msg['Text'].replace("@"+config.nick_name, ""),
            'userid': msg['FromUserName'][3:10]}

    encode = urllib.parse.urlencode(data).encode(encoding='UTF8')
    request = urllib.request.urlopen(url, encode)
    response = request.read()
    message = read_message(response)

    print(">>> " + message)

    return message


def read_message(response):
    data = json.loads(response, encoding='UTF8')
    code = data['code']
    if code == 200000 or code == 302000 or code == 308000:
        massage = data['text'] + ":\n" + data['url']
    else:
        massage = data['text']
    return "[自动回复] " + massage


def is_first_chat(user_id):
    if user_id in config.chat_list:
        return False
    else:
        config.chat_list.append(user_id)
        return True
